package com.qf.sl.youshare.tasks;

import android.os.AsyncTask;
import com.qf.sl.youshare.Constants;
import com.qf.sl.youshare.utils.HttpTools;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Created by IDEA
 * User : sl
 * on 2015/2/5.
 * 11:04
 */

/**
 * 获取产品列表接口调用,这个异步任务在
 *  核心产品与平台产品都使用到了
 */
public class ProductListTask extends AsyncTask<String, Integer, JSONObject> {

    private TaskProcessor processor;

    public ProductListTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        JSONObject ret = null;

        if (params != null && params.length>0) {
            //产品列表接口支持指定分类列表ID,
            //  用于获取指定分类下的产品列表
            String id = params[0];

            String size = "5";
            String page = "1";

            switch (params.length){
                case 2:
                    size = params[1];
                    break;
                case 3:
                    size = params[1];
                    page = params[2];
                    break;
                default:
                    break;
            }

            //GET 请求采用 参数: key=value&key=value
            String url = Constants.CATEGORY_URL
                            + id
                            + "&size=" + size
                            + "&page=" + page;
            byte[] bytes = HttpTools.get(url);
            if (bytes != null) {
                try {
                    String str = new String(bytes,"UTF-8");
                    ret = new JSONObject(str);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        if (processor != null) {
            processor.processResult(jsonObject);
        }
    }
}
